// 该变量用于生成图片时给予的独立data-id
var tempI = 1,
    tempJ = 0,
    // 最大上传图片数量
    maxCount = 9,
    //上传文件
    $uploaderFiles = $('.weui_uploader_files'),
    // 本地图片信息数组
    URLARR = [],
    // 微信服务器端返回图片信息数组
    SERVERARR = [];

$(function () {
    // 微信SDK 上传图片
    Model.wechat.weImage();
    // 获取用户信息
    var result = Model.user.getUserInfo();
    if (!sessionStorage.getItem('hmdj_stopError')) {
        sessionStorage.setItem('hmdj_stopError', true);
    } else {
        if (result.code) {
            Common.fn.formatOutput(result);
            loading.hide();
            return false;
        }
    }
    // 设置初始是否包邮状态
    $('#sendState-btn').val('off');
    $('#sendState').val('false');
    // 将开关置为开启状态
    $('#sendState-btn').click();
    // 弹出提示
    if (result.data.auth) {
		$('.is-auth').text('已认证')
		weui.alert('认证商家每天可以发布100单商品')
		$('.is-auth').on('click', function() {
			location.href = 'authentication2.html'
		})
	} else {
		$('.is-auth').text('未认证（免费认证）')
		weui.alert('未认证商家每天仅可以发布10单商品，认证后将提高限额')
		$('.is-auth').on('click', function() {
			location.href = 'authentication.html'
		})
	}
});

// 产品分类
$(document).on('click', '#showPicker', function () {
    $('.classify-block').css('display', 'block');
});

// 产品父目录
$(document).on('click', '.start-classify-item', function () {
    var id = $(this).attr('data-id');
    $('.classify-items-1').css('display', 'none');
    for (var i = 0; i < Config.classify[id].length; i++) {
        var item = '<a href="javascript:;" class="end-classify-item" data-classify1="';
        switch (id) {
            case '_1':
                item += '茶酒滋补';
                break;
            case '_2':
                item += '工艺作品';
                break;
            case '_3':
                item += '花鸟文娱';
                break;
            case '_4':
                item += '书画篆刻';
                break;
            case '_5':
                item += '文玩古玩';
                break;
            case '_6':
                item += '珠宝玉器';
                break;
            case '_7':
                item += '紫砂陶瓷';
                break;
        }
        item += '" data-classify2="' + Config.classify[id][i].title + '" data-id="' + Config.classify[id][i].id + '">' + Config.classify[id][i].title + '</a>';
        $('.classify-items-2').append(item);
    }
});

// 产品子目录
$(document).on('click', '.end-classify-item', function () {
    var id = $(this).attr('data-id'),
        classify1 = $(this).attr('data-classify1'),
        classify2 = $(this).attr('data-classify2');
    $('.classify-items-2').empty();
    $('.classify-items-1').css('display', 'block');
    $('#showPicker').text(classify1 + ' < ' + classify2);
    $('#classify').val(id);
    $('.classify-block').css('display', 'none');
});

// 分类目录关闭按钮
$(document).on('click', '.classify-close-btn', function () {
    $('.classify-items-2').empty();
    $('.classify-items-1').css('display', 'block');
    $('.classify-block').css('display', 'none');
});

// 包邮状态
$(document).on('click', '#sendState-btn', function () {
    if ($(this).val() == 'off') {
        $(this).val('on');
        $('#sendState').val('true');
    } else {
        $(this).val('off');
        $('#sendState').val('false');
    }
});

// 发布商品
$(document).on('click', '#showTooltips', function () {
    // 数据验证
    var params = {
        classify: $('#classify').val(),
        detail: $.trim($('.detail').val()),
        downPrice: parseInt($.trim($('.down-price').val())),
        upPrice: parseInt($.trim($('.up-price').val())),
        sendState: $('#sendState').val()
    };
    for (var i in params) {
        if (params[i] == '') {
            weui.alert('产品信息不得为空');
            return false;
        }
        if (i == 'downPrice' || i == 'upPrice') {
            if (params[i] <= 0) {
                weui.alert('拍卖价格不符合规范');
                return false;
            }
            if (params.downPrice > params.upPrice) {
                weui.alert('起降价不得低于保底价');
                return false;
            }
        }
    }
    // 价格格式验证
    var d = params.downPrice,
        u = params.upPrice,
        regu = "^[0-9]+[\.][0-9]{0,3}$",
        re = new RegExp(regu);
    if (d.toString().indexOf('.') < 0) {
        d += '.00';
    }
    if (!re.test(d)) {
        weui.alert('保底价格式有误');
        return false;
    }
    if (u.toString().indexOf('.') < 0) {
        u += '.00';
    }
    if (!re.test(u)) {
        weui.alert('起降价格式有误');
        return false;
    }
    // 图片验证
    if (URLARR.length < 1) {
        weui.alert('请至少上传一张图片');
        return false;
    }
    // 保存数据至sessionStorage
    var publish = {
        cid: params.classify,
        content: params.detail,
        topPrice: params.upPrice,
        botPrice: params.downPrice,
        proxy: false,
        charges: '',
        stock: '',
        postage: params.sendState
    }
    // 更改按钮样式
    $('#showTooltips').text('图片上传中...');
    // 上传图片至微信服务器
    /* for (var i = 0; i < URLARR.length; i++) {
        (function(i){
            wx.uploadImage({
                localId: URLARR[i].title, // 需要上传的图片的本地ID，由chooseImage接口获得
                isShowProgressTips: 0, // 默认为1，显示进度提示
                success: function (res) {
                    alert('第 ' + i + ' 上传服务器成功');
                    var serverId = res.serverId;
                    SERVERARR.push(serverId);
                },
                error: function () {
                    weui.alert('图片' + URLARR[i].title + '上传失败。');
                    $('#showTooltips').text('重新发布');
                    return false;
                }
            });
        })(i);
    } */
    var loading = weui.loading('loading', {
        className: 'custom-classname'
    });
    function uploadToWechat(publish) {
        wx.uploadImage({
            localId: URLARR[tempJ].title, // 需要上传的图片的本地ID，由chooseImage接口获得
            isShowProgressTips: 0, // 默认为1，显示进度提示
            success: function (res) {
                var serverId = res.serverId;
                SERVERARR.push(serverId);
                tempJ++;
                if (URLARR.length != tempJ) {
                    uploadToWechat(publish);
                } else {
                    $('#showTooltips').text('发布');
                    var good_img = SERVERARR;
                    // 调用接口，将真实图片地址push至good_img中
                    publish['good_img'] = good_img;
                    sessionStorage.setItem('hmdj_publish', JSON.stringify(publish));
                    location.href = 'release2_product.html';
                }
            },
            error: function () {
                weui.alert('图片' + URLARR[tempJ].title + '上传失败。');
                $('#showTooltips').text('重新发布');
                return false;
            }
        });
    }
    uploadToWechat(publish);
});

// 协议按钮
$(document).on('click', '.agreement-btn', function () {
    $('.shade').css('display', 'block');
    $('.xieyi-content').css('display', 'block');
    $('.xieyi-content').html(Common.pa._MESSAGE);
});

// 关闭协议按钮
$(document).on('click', '.xieyi-close-btn', function () {
    $('.shade').css('display', 'none');
    $('.xieyi-content').css('display', 'none');
});

// 上传图片按钮
$(document).on('click', '#upload-btn', function () {
    chooseImg();
});

// 删除图片按钮
$(document).on('click', '.close-btn', function () {
    var id = $(this).attr('data-id');
    // 删除数组中该图片
    for (var i = 0; i < URLARR.length; i++) {
        if (URLARR[i].id == id) {
            URLARR.splice(i, 1);
        }
    }
    // 删除缩略图
    $(this).parent().remove();
});

// 选择图片
function chooseImg() {
    wx.chooseImage({
        count: 9,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: function (res) {
            // 遍历产生图片
            var length = res.localIds.length;
            for (var i = 0; i < length; i++) {
                // 判断是否达到图片最大值
                if (URLARR.length >= maxCount) {
                    weui.alert('一共只能上传' + maxCount + '张图片。');
                    return false;
                }
                // 获取选中的图片
                var localId = res.localIds[i],
                    localData = '';
                if (window.__wxjs_is_wkwebview) {
                    // IOS用图片选择及显示
                    wx.getLocalImgData({
                        localId: localId,
                        success: function (res) {
                            localData = res.localData;
                            localData = localData.replace('jgp', 'jpeg');
                            // 生成图片
                            var item = '<li class="weui_uploader_file" style="background-image:url(' + localData + ');position: relative;"><a href="javascript:;" class="close-btn" data-id="' + tempI + '"><img src="../img/icon/close.png" class="upload-item-close"></a></li>';
                            $uploaderFiles.append(item);
                        },
                        fail: function (res) {
                            alert(res.errMsg);
                        }
                    });
                } else {
                    // Android用图片显示
                    localData = localId;
                    // 生成图片
                    var item = '<li class="weui_uploader_file" style="background-image:url(' + localData + ');position: relative;"><a href="javascript:;" class="close-btn" data-id="' + tempI + '"><img src="../img/icon/close.png" class="upload-item-close"></a></li>';
                    $uploaderFiles.append(item);
                }
                // 将生成的图片存入数组
                var item = {
                    id: tempI,
                    title: localId
                };
                URLARR.push(item);
                tempI++;
            }
        }
    });
}

